package services

import (
	"pegasus/models"
	"pegasus/utils"
	"time"

	"github.com/go-xorm/xorm"
)

//CharacterService 目前主要用来定时执行任务
type CharacterService struct {
	utils.ILogger
	engine *xorm.Engine
}

//NewCharacterService 返回CharacterService
func NewCharacterService(il utils.ILogger, engine *xorm.Engine) *CharacterService {
	return &CharacterService{
		ILogger: il,
		engine:  engine,
	}
}

//UpdatePeriod 定时检测卡是否过期
func (srv *CharacterService) UpdatePeriod() {
	go func() {
		srv.updatePeriod(utils.GetTodayZero())
		for {
			//每天凌晨执行任务
			now := time.Now()
			zeroToday := utils.GetTodayZero()
			zeroTomorrow := zeroToday.AddDate(0, 0, 1)
			d := zeroTomorrow.Sub(now)
			srv.Tracef("sleep:%d", d)
			time.Sleep(d)
			srv.updatePeriod(zeroTomorrow)
		}
	}()
}

func (srv *CharacterService) updatePeriod(zero time.Time) {
	for {
		ctnue := true
		err := utils.Transaction(srv.engine, func(si *xorm.Session) error {
			bean := &models.CharacterBean{}
			found, err := si.Where("PeriodExpireTime < ? and PeriodType != ?", zero, models.CharacterNormal).Get(bean)
			if err != nil {
				return err
			}
			if !found {
				ctnue = false
				return nil
			}
			//卡已经过期
			bean.PeriodType = models.CharacterNormal
			_, err = si.ID(bean.ID).Cols("PeriodType").Update(bean)
			return err
		})
		if err != nil {
			time.Sleep(50 * time.Millisecond)
		}
		//任务结束
		if !ctnue {
			break
		}
	}
}
